<template>
  <!-- 弹出层 -->
  <van-popup v-model="show" position="bottom" round @close="close">
    <!-- 多选复选框 -->

    <div class="checkbox-group">
      <van-checkbox-group v-model="selectedUserIds">
        <van-cell-group>
          <van-cell clickable v-for="item in optios" :key="item.id" :title="item[keyOption.name]">
            <template #right-icon>
              <van-checkbox :name="item[keyOption.id]" shape="square" />
            </template>
          </van-cell>
        </van-cell-group>
      </van-checkbox-group>
    </div>

    <van-empty description="暂无数据" v-if="!optios.length" />


    <!-- 确认按钮 -->
    <van-button block type="primary" @click="handleSelectedUsers">{{ optios.length?"确认选择":"取消"}}</van-button>
  </van-popup>
</template>

<script>
import Vue from 'vue';
import { Checkbox, CheckboxGroup } from 'vant';
Vue.use(Checkbox);
Vue.use(CheckboxGroup);
export default {
  props: {
    // // 父组件传递的已选用户 ID 列表
    // confirmSelection: {
    //   type: Function,
    //   required: true
    // },
    // showPopup: {
    //   type: Boolean,
    //   default: false
    // },
    ids: {
      type: String,
      default: ""
    },
    // 用户列表
    optios: {
      type: Array,
      default: () => [
        { id: "admin", name: '王五' },
        { id: "jeecg", name: '赵六' }
      ]
    },
    keyOption: {
      type: Object,
      default: () => ({ id: 'id', name: 'name' })
    }
  },

  data() {
    return {
      show: true,
      // 已选用户 ID 列表
      selectedUserIds: this.ids?.split?.(",") || [],
    };
  },
  // watch: {
  //   // 监听父组件传递的 props 变化
  //   showPopup(newVal) {
  //     this.show = newVal;
  //   }
  // },
  methods: {
    // 确认选择
    // confirmSelection() {
    //   console.log('已选用户:', this.selectedUsers);
    //   this.showPopup = false; // 关闭弹出层
    // }
    // 根据已选 ID 获取对应的用户信息
    handleSelectedUsers() {
      const selectedUsers = this.optios.filter(user => this.selectedUserIds.includes(user.id));
      const data = selectedUsers.reduce((acc, user) => ({ id: [...acc.id, user[this.keyOption.id]], name: [...acc.name, user[this.keyOption.name]] }), { id: [], name: [] });
      this.$emit('close', { id: data.id.join(","), name: data.name.join("、") })
    },
    close() {
      this.$emit('close', "")
    }
  }
}
</script>

<style scoped lang="less">
.checkbox-group {
  max-height: calc(100% - 100px);
  overflow: auto;
}
</style>